﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using LimaLims.Application.Service.Basic.Dto;
using LimaLims.Core.Entity.Basic;
using LimaLims.Core;
using Microsoft.AspNetCore.Mvc;
using Mapster;
using Microsoft.EntityFrameworkCore;
using Furion.DatabaseAccessor.Extensions;
using LimaLims.Application.Service.Sys;
using LimaLims.Core.Enum;
using LimaLims.Application.Service.Base.Dto;
using System.Linq;

namespace LimaLims.Application.Service.Basic
{
    /// <summary>
    /// 不良原因服务
    /// </summary>
    [ApiDescriptionSettings(Name = "DefectiveReason", Order = 163)]
    [Route("api")]
    public class DefectiveReasonService : IDefectiveReasonService, IDynamicApiController, ITransient
    {
        private readonly IRepository<DefectiveReason> _defectiveReasonRep;  // 不良原因表仓储
        private readonly IGenerateCodeUtilService _generateCodeUtilService;//编码规则

        public DefectiveReasonService(IRepository<DefectiveReason> defectiveReasonRep, IGenerateCodeUtilService generateCode)
        {
            _defectiveReasonRep = defectiveReasonRep;
            _generateCodeUtilService = generateCode;
        }

        /// <summary>
        /// 新增
        /// </summary>
        [HttpPost("defectiveReason/add")]
        public async Task Add(AddDefectiveReasonInput input)
        {
            var isExist = await _defectiveReasonRep.DetachedEntities.AnyAsync(u => u.Code == input.Code);
            if (isExist)
                throw Oops.Oh("已存在相同编号的原因！");

            if (string.IsNullOrWhiteSpace(input.Code))
            {
                input.Code = await _generateCodeUtilService.GenerateCode(BusinessType.DefectiveReason);
            }

            var defectiveReason = input.Adapt<DefectiveReason>();

            await defectiveReason.InsertAsync();
        }

        [HttpPost("defectiveReason/delete")]
        public async Task Delete(long id)
        {
            var defectiveReason = await _defectiveReasonRep.FirstOrDefaultAsync(u => u.Id == id);
            if (defectiveReason == null)
                throw Oops.Oh("不存在此数据");

            await defectiveReason.DeleteAsync();
        }

        [HttpGet("defectiveReason/detail")]
        public async Task<DefectiveReason> Detail(long id)
        {
            var defectiveReason = await _defectiveReasonRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == id);
            if (defectiveReason == null)
                throw Oops.Oh("不存在此数据");

            return defectiveReason;
        }

        [HttpPost("defectiveReason/edit")]
        public async Task Edit(EditDefectiveReasonInput input)
        {
            var defectiveReason = await _defectiveReasonRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
            if (defectiveReason == null)
                throw Oops.Oh("不存在此数据！");

            var isExist = await _defectiveReasonRep.DetachedEntities.AnyAsync(u => u.Code == input.Code && u.Id != input.Id);
            if (isExist)
                throw Oops.Oh("已存在相同编号的原因！");

            var defectiveReasonModel = input.Adapt<DefectiveReason>();

            await defectiveReasonModel.UpdateAsync();
        }

        /// <summary>
        /// 下拉数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("defectiveReason/selectList")]
        public async Task<List<SelectDto>> SelectList()
        {
            var list = await _defectiveReasonRep.DetachedEntities.Where(s => s.ValidStatus == true).OrderBy(s => s.Sort).ToListAsync();
            return list.Select(x => new SelectDto
            {
                Value = x.Id,
                Label = x.Reason
            }).ToList();
        }

        [HttpGet("defectiveReason/page")]
        public async Task<PageResult<DefectiveReasonOutput>> QueryPage([FromQuery] DefectiveReasonPageInput input)
        {
            var name = !string.IsNullOrEmpty(input.SearchValue?.Trim());
            var code = !string.IsNullOrEmpty(input.Code?.Trim());
            var items = await _defectiveReasonRep.DetachedEntities
                                         .Where((name, u => EF.Functions.Like(u.Reason, $"%{input.SearchValue.Trim()}%")))
                                         .Where((code, u => EF.Functions.Like(u.Code, $"%{input.Code.Trim()}%")))
                                         .Where(input.ValidStatus.HasValue, u => u.ValidStatus==input.ValidStatus)
                                         .OrderBy(u => u.Sort)
                                         .Select(u => new DefectiveReasonOutput
                                         {
                                             Id = u.Id,
                                             Code = u.Code,
                                             Reason = u.Reason,
                                             ValidStatus = u.ValidStatus,
                                             Sort = u.Sort,
                                             Remark = u.Remark,
                                             CreatedTime=u.CreatedTime,
                                             CreatedUserName=u.CreatedUserName,
                                             UpdatedTime=u.UpdatedTime,
                                             UpdatedUserName=u.UpdatedUserName
                                         }).ToADPagedListAsync(input.PageNo, input.PageSize);

            return items;
        }

    }
}
